package com.gin.kotlin.gf2gamecommunity.base.composable

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

/**
 * 使用DropdownMenu实现的下拉选择器
 * @param T 备选项目类型
 * @param list 备选列表
 * @param initValue 初始值
 * @param onSelected 选中时回调
 * @param toText 项目名称
 */
@Composable
fun <T> DropdownMenuSelector(list: List<T>, initValue: T? = null, onSelected: (item: T) -> Unit, toText: (item: T?) -> String) {
    var activeValue by remember { mutableStateOf(initValue) }
    var expanded by remember { mutableStateOf(false) }
    Box {
        BorderCard(modifier = Modifier.clickable { expanded = !expanded }) {
            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(4.dp)) {
                Text(toText(activeValue))
                Icon(if (expanded) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown, contentDescription = null)
            }
        }
        DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
            list.forEach { item ->
                DropdownMenuItem(text = {
                    Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                        Text(toText(item))
                        if (activeValue == item) Icon(Icons.Filled.Check, contentDescription = null)
                    }
                }, onClick = {
                    expanded = false
                    activeValue = item
                    onSelected(item)
                })
            }
        }
    }
}